#!/usr/bin/env bash
# Author: jackzang
# mail: jackzang@aishangwei.net
# Date: 2020/2/9

set -e

#######################
export KEY_COUNTRY="China"
export KEY_PROVINCE="HeNan"
export KEY_CITY="ZhenZhou"
export KEY_ORG="xiodi"
export KEY_EMAIL="ca@aishangwei.net"
INTERNAL_IP1="192.168.20.0 255.255.255.0"
INTERNAL_IP2="192.168.30.0 255.255.255.0"
INTERNAL_DNS1="192.168.20.250"
INTERNAL_DNS1="114.114.114.114"
########################


# 配置环境
systemctl disable firewalld && systemctl stop firewalld
sed -i "/^SELINUX/s/enforcing/disabled/" /etc/selinux/config
setenforce 0
echo net.ipv4.ip_forward = 1 >> /etc/sysctl.conf
sysctl -p

# 安装软件
yum -y install epel-release
yum -y install openvpn easy-rsa

# 生成 OpenVPN 所需证书以及文件
cp -r /usr/share/easy-rsa/ /etc/openvpn/
cd /etc/openvpn/easy-rsa/3/
./easyrsa init-pki
./easyrsa build-ca nopass

# 生成 OpenVPN 服务器证书和密钥
./easyrsa build-server-full server nopass

# 生成 Diffie-Hellman 算法需要的密钥文件
./easyrsa gen-dh

# 生成 tls-auth Key,主要用来防止 Dos 和 TLS 攻击(可选)
openvpn --genkey --secret ta.key

# 日志目录配置
mkdir -p /var/log/openvpn
chown openvpn:openvpn /var/log/openvpn

# 相关文件整理（为了维护方便）
mkdir /etc/openvpn/server/certs && cd /etc/openvpn/server/certs/
cp /etc/openvpn/easy-rsa/3/pki/dh.pem /etc/openvpn/easy-rsa/3/pki/ca.crt ./
cp /etc/openvpn/easy-rsa/3/pki/issued/server.crt ./
cp /etc/openvpn/easy-rsa/3/pki/private/server.key ./
cp /etc/openvpn/easy-rsa/3/ta.key ./

# openvpn 启动配置文件
cat>/etc/openvpn/server.conf<<EOF
port 1194
proto udp
dev tun
ca /etc/openvpn/server/certs/ca.crt
cert /etc/openvpn/server/certs/server.crt
key /etc/openvpn/server/certs/server.key
dh /etc/openvpn/server/certs/dh.pem
tls-auth /etc/openvpn/server/certs/ta.key 0
server 10.8.0.0 255.255.255.0
ifconfig-pool-persist ipp.txt
push ${INTERNAL_IP1}
push ${INTERNAL_IP2}
push "dhcp-option DNS ${INTERNAL_DNS1}"
push "dhcp-option DNS ${INTERNAL_DNS2}"
compress lzo
duplicate-cn
keepalive 10 120
comp-lzo
persist-key
persist-tun
user openvpn
group openvpn
log /var/log/openvpn/server.log
log-append /var/log/openvpn/server.log
status /var/log/openvpn/status.log
verb 3
explicit-exit-notify 1
EOF

# 服务开机自启
systemctl start openvpn@server
systemctl enable openvpn@serve

exit 0
